package com.tiyende.credit.loop.ui.fragment

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonFragment
import com.tiyende.credit.loop.databinding.TiyendeFragmentUserCenterBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.activity.TiyendeAppSettingActivity
import com.tiyende.credit.loop.ui.activity.TiyendeFeedbackActivity
import com.tiyende.credit.loop.ui.activity.TiyendeProfileActivity
import com.tiyende.credit.loop.ui.dialog.TiyendeLanguageDialog
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TiyendeCustomDataHelper
import com.tiyende.credit.loop.utils.helper.TiyendeLanguageHelper
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：我的
 */
class TiyendeUserCenterFragment(): CommonFragment() {
//    lateinit var binding: TiyendeFragmentUserCenterBinding
    // 使用可空类型的 backing property
    private var _binding: TiyendeFragmentUserCenterBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var drawerLayout: DrawerLayout? = null

    constructor(drawerLayout: DrawerLayout): this(){
        this.drawerLayout = drawerLayout
    }
    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentUserCenterBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        initMeRefrashView()

        val zoneCode = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_CODE)
        val zoneCountry = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_COUNTRY)
        //只有柬埔寨支持语言切换
        if (zoneCode == "855" || zoneCountry == "cambodia"){
            _binding?.userCenterSwitchLanguageLayout?.visibility = View.VISIBLE
        } else {
            _binding?.userCenterSwitchLanguageLayout?.visibility = View.GONE
        }
    }

    override fun initTiyendeListener() {
        _binding?.userCenterCloseView?.setOnClickListener {
            drawerLayout?.closeDrawer(GravityCompat.START)
        }

        _binding?.userCenterProfileLayout?.setOnClickListener {
            onIntent(TiyendeProfileActivity::class.java)
        }

        _binding?.userCenterFinanciaAccountsLayout?.setOnClickListener {
//            _binding?.userCenterProfileLayout.callOnClick()
            if (TiyendeProcessHelper.queryTiyendeAuthenticationStepList().size == 0) {//流程已完成 - 提示
                showErrorTipsDialog(getString(R.string.tiyende_user_center_profile_complete_tips),"User Center Click Information")
            } else {
                //流程未完成 - 进入流程页面
                _binding?.userCenterCloseView?.callOnClick()
                launch(Dispatchers.Main){
                    delay(300)
                    publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_SHOW_AUTHENTICATION))
                }
            }
        }

        //切换语言
        _binding?.userCenterSwitchLanguageLayout?.setOnClickListener {
            showTiyendeLanguageDialog()
        }

        _binding?.userCenterFeedbackLayout?.setOnClickListener {
            onIntent(TiyendeFeedbackActivity::class.java)
        }
        _binding?.userCenterAppSettingLayout?.setOnClickListener {
            onIntent(TiyendeAppSettingActivity::class.java)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun loadTiyendeData() {
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_CENTER_START)
        //加载保存自定义数据
        TiyendeCustomDataHelper.queryTiyendeCustomDataAction()

        //是否有版本更新
        _binding?.userCenterNewVersionPoint?.visibility = View.GONE
        if (TiyendeConfigsHelper.isTiyendeUpdate()){
            _binding?.userCenterNewVersionPoint?.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initMeRefrashView() {
        _binding?.meRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.meRefreshLayout?.setOnRefreshListener {
            TiyendeCustomDataHelper.queryTiyendeCustomDataAction()
        }
    }

    /**
     * 语言切换
     */
    private fun showTiyendeLanguageDialog(){
        val dataList = TiyendeLanguageHelper.queryTiyendeLanguageList()
        val languageDialog = TiyendeLanguageDialog(requireContext(),"User Center page",object : TiyendeLanguageDialog.IDialogCallback{
            override fun onLanguageSelectedItem(data: JSONObject) {
                val tags = data.optString("tags")
                TiyendeLanguageHelper.saveTiyendeLanguage(tags)
            }
        })
        languageDialog.setCancelable(true)
        languageDialog.setCanceledOnTouchOutside(true)
        languageDialog.show()
        languageDialog.addTiyendeLanguageList(dataList)
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        if (event.eventType == TiyendeEventData.TYPE.TIYENDE_CUSTOM_DATA_REFRESHED){
            hiddenTiyendeLoading()
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        _binding?.meRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_CENTER_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}